<?php

namespace Desktopd\MUA;


// TemporaryFile
class TemporaryFile {
    protected $fd;
    
    public function __construct () {
        $this->fd = tmpfile();
        if (!is_resource($this->fd)) {
            throw new \RuntimeException('Could not open a temporary file');
        }
    }
    
    public function write ($data) {
        return fwrite($this->fd, $data) && fflush($this->fd);
    }
    
    public function read () {
        rewind($this->fd);
        return stream_get_contents($this->fd);
    }
    
    public function getPath () {
        return stream_get_meta_data($this->fd)['uri'];
    }
    
    public function __destruct () {
        rewind($this->fd);
        $stat = fstat($this->fd);
        for ($i = 0; $i < $stat['blocks']; $i++) {
            fwrite($this->fd, str_repeat("\xff", $stat['blksize']));
        }
    }
}


// vim: ts=4 et ai

